package org.spring.aicloud.controller;

import ch.qos.logback.core.util.TimeUtil;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.net.NetUtil;
import cn.hutool.crypto.SecureUtil;
import io.minio.errors.*;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.spring.aicloud.util.MinioUtil;
import org.spring.aicloud.util.NameUtil;
import org.spring.aicloud.util.ResponseEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/captcha")
@Tag(name = "生成验证码控制器")
public class CaptchaController {
    @Resource
    private MinioUtil minioUtil;
    @Qualifier("redisTemplate")
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 生成验证码图片
     */
    @RequestMapping("/create")
    public ResponseEntity create(HttpServletRequest request) throws ServerException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException, IOException {
        String url = "";
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(120,40);
        String fileName = NameUtil.getCaptchaName(request); //针对于同一个ip生成一样的图片名
        try(InputStream inputStream = new ByteArrayInputStream(lineCaptcha.getImageBytes())){
            url = minioUtil.upload(fileName,inputStream,"image/png");
            String code = lineCaptcha.getCode(); //得到验证码
            redisTemplate.opsForValue().set(fileName,code); //将验证码保存到redis中
        }
        return ResponseEntity.success(url);
    }

}
